package excel.util;


import com.usian.common.exception.CatchConsumerException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class PageUtils {
    //每个sheet最多导出多少条数据
    public static final int SHEET_COUNT = 2;


    /**
     * 写excel. 拆分多个sheet
     * xls方式
     * @param response 响应流
     * @param fileName 文件名称
     * @param titleColumn 对应bean的属性名
     * @param titleName   excel要导出的列名
     * @param titleSize   列宽
     * @param dataList    数据
     */
    public static void exportExcel(HttpServletResponse response, String fileName, String titleColumn[], String titleName[], int titleSize[], List<?> dataList) {
        //添加Worksheet（不添加sheet时生成的xls文件打开时会报错)
        SXSSFWorkbook workbook = new SXSSFWorkbook();

        OutputStream out = null;
        try{
            //新建文件
            out = response.getOutputStream();
            String lastFileName = fileName + ".xlsx";
            response.setContentType("application/msexcel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + URLEncoder.encode(lastFileName, "UTF-8"));
            int k = 0;
            int rowIndex;
            Sheet sheet = workbook.createSheet(fileName + (k + 1));
            //写入excel的表头
            Row titleNameRow = workbook.getSheet(fileName + (k + 1)).createRow(0);
            //设置样式
            CellStyle titleStyle = workbook.createCellStyle();
            for (int i = 0; i < titleName.length; i++) {
                Cell cell = titleNameRow.createCell(i);
                cell.setCellStyle(titleStyle);
                cell.setCellValue(titleName[i]);
            }

            //通过反射获取数据并写入到excel中
            if (dataList != null && dataList.size() > 0) {
                if (titleColumn.length > 0) {
                    for (int index = 0; index < dataList.size(); index++) {
                        //设置多个sheet
                        //每个sheet3W条数据
                        if (index != 0 && (index) % SHEET_COUNT == 0) {
                            k = k + 1;
                            sheet = workbook.createSheet(fileName + (k + 1));
                            //写入excel的表头
                            titleNameRow = workbook.getSheet(fileName + (k + 1)).createRow(0);
                            for (int i = 0; i < titleName.length; i++) {
                                sheet.setColumnWidth(i, titleSize[i] * 256);    //设置宽度
                                Cell cell = titleNameRow.createCell(i);
                                cell.setCellStyle(titleStyle);
                                cell.setCellValue(titleName[i]);
                            }
                        }
                        if (index < SHEET_COUNT) {
                            rowIndex = index + 1;
                        } else {
                            rowIndex = index - SHEET_COUNT * ((index) / SHEET_COUNT) + 1;
                        }

                        Object obj = dataList.get(index);     //获得该对象
                        Class clsss = obj.getClass();     //获得该对对象的class实例
                        Row dataRow = workbook.getSheet(fileName + (k + 1)).createRow(rowIndex);
                        for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
                            String title = titleColumn[columnIndex].toString().trim();
                            if (!"".equals(title)) {  //字段不为空
                                //使首字母大写
                                String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1, title.length());
                                // 使其首字母大写;
                                String methodName = "get" + UTitle;

                                // 设置要执行的方法
                                Method method = clsss.getDeclaredMethod(methodName);

                                //获取返回类型
                                String returnType = method.getReturnType().getName();
                                Object object = method.invoke(obj);
                                String data = method.invoke(obj) == null ? "" : object.toString();
                                Cell cell = dataRow.createCell(columnIndex);
                                if (data != null && !"".equals(data)) {
                                    if ("int".equals(returnType)) {
                                        cell.setCellValue(Integer.parseInt(data));
                                    } else if (Date.class.getName().equals(returnType)) {
                                        cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(object));
                                    } else {
                                        cell.setCellValue(data);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                   CatchConsumerException.catchException(20003,"导出报错");
                }
            }
        }
    }
}
